<template>
  <div id="container">
    <h1>num：{{ num }}</h1>
    <button @click="exportExcel">导出 Excel(不阻塞数的累加执行)</button>
    <br>
    <button @click="exportExcelNoWorker">导出 Excel(no worker)</button>
    <br>
    <button @click="exportExcelNoWorker2">
      导出 Excel(no worker And不转文件流)
    </button>
    <div>
      <input style="width:100%" />
    </div>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import json2Excel, { s2ab, exportOfBlob } from "@/util/index";
import exportDataWorker from "worker-loader!../../worker/getExportData.js";
// key -> name 的映射
const excelKeyToName = {
  name: "姓名",
  age: "年龄",
  skill: "特长",
  telephone: "电话",
  address: "地址",
};
export default {
  data() {
    return {
      jsonData: [],
      num: 0,
    };
  },
  created() {
    setInterval(() => {
      this.num++;
    });
  },
  methods: {
    exportExcel() {
      // 使用web-worker
      const worker = new exportDataWorker();
      worker.postMessage({ num: 199999, excelKeyToName });
      worker.addEventListener("message", (e) => {
        worker.terminate();
        console.time("test");
        FileSaver.saveAs(e.data.data.xlsxBlob, `${123}.xlsx`);
        console.timeEnd("test");
      });
    },
    exportExcelNoWorker() {
      // 没使用web-worker
      console.time("test-noWorker");
      const jsonData = [];
      for (let i = 0; i < 199999; i++) {
        jsonData.push({
          name: `大伟${i + 1}`,
          age: 1 + i,
          skill: `前端${i}`,
          telephone: 2020083 + i,
          address: `北京${i}`,
        });
      }
      console.log("jsonData", jsonData);
      const wbout = exportOfBlob({ jsonData, excelKeyToName })
      FileSaver.saveAs(
        new Blob([s2ab(wbout)], {
          // type: 'application/octet-stream'
          type: "",
        }),
        `${123}.xlsx`
      );
      console.timeEnd("test-noWorker");
    },
    // 导出 Excel 文件不轉文件流
    exportExcelNoWorker2() {
      const jsonData = [];
      for (let i = 0; i < 15000; i++) {
        jsonData.push({
          name: `大伟${i + 1}`,
          age: 1 + i,
          skill: `前端${i}`,
          telephone: 2020083 + i,
          address: `北京${i}`,
        });
      }
      // 格式化参数
      const data = jsonData.map((item) => {
        const newItem = {};
        Object.keys(item).forEach((key) => {
          newItem[excelKeyToName[key]] = item[key];
        });
        return newItem;
      });
      // 导出 Excel
      json2Excel(data);
    },
  },
};
</script>
